package br3akr.DeadlyDinnerParty.Client;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;

import br3akr.DeadlyDinnerParty.Common.UpdateClient;

public class Client {
	public static void main(String[] args) throws IOException {
        /* Use an appropriate Look and Feel */
        //Create and set up the window.
        ClientGUI clientGUI = new ClientGUI("The Deadly Dinner Party");
        clientGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
        /* Uncomment me if you want the sound handler to fire off */
		//SoundHandler sh = new SoundHandler();
		//Thread t = new Thread(sh);
		//t.start();
        
		Socket socket = null;
		PrintWriter out = null;
		ObjectInputStream in = null;
		BufferedReader stdIn = null;
		String hostName = args[0];
		int port = 4444;
		
		try {
			socket = new Socket(hostName, port);
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new ObjectInputStream(socket.getInputStream());
			clientGUI.setPrintWriter(out);
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host: " + hostName);
			System.exit(1);
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("Couldn't get I/O for the connection to " + hostName);
			System.exit(1);
		}
		
		try {
			stdIn = new BufferedReader(new InputStreamReader(System.in));
			UpdateClient fromServer;
			while ((fromServer = (UpdateClient)in.readObject()) != null || true) {
				clientGUI.updateClient(fromServer);
			}
		} catch (EOFException e) {
			UpdateClient uc = new UpdateClient("\n\nConnection to the server has been lost.", null, null, null, null, null, null, null, null, null, false);
			clientGUI.updateClient(uc);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("An exception has occurred: " + e);
		} finally {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
			if (stdIn != null) {
				stdIn.close();
			}
			if (socket != null) {
				socket.close();
			}
		}
	}
}